package www.wen.com.common.lib.base.activity

import android.os.Bundle
import androidx.databinding.ViewDataBinding
import com.dylanc.loadingstateview.ViewType
import com.lxj.xpopup.XPopup
import com.orhanobut.logger.Logger
import www.wen.com.common.R
import www.wen.com.common.lib.base.module.BaseViewModel
import www.wen.com.common.lib.data.entities.*
import www.wen.com.common.lib.data.entities.builtIn.*
import www.wen.com.common.lib.extension.toast
import www.wen.com.common.lib.helper.CreateXPopupHelper
import www.wen.com.common.lib.helper.PopupViewEntity
import www.wen.com.common.lib.helper.loading.ErrorAdapter
import www.wen.com.common.lib.view.popuview.CustomLoadingPopupView
import www.wen.com.common.lib.view.popuview.ILoading


/**
 * @author WEN
 * @Description: 这是一个通用加载框的Activity，由viewModel通过livedata来发起,如果页面需要发起请求弹出标准加载框的请继承这个基类
 * @date 2020/11/1 21:54
 */
abstract class BaseLoadingActivity<K : ViewDataBinding> : BaseActivity<K>() {

    abstract val viewModel: BaseViewModel

    private var mLoadingPopupView: ILoading? = null

    /**
     * 是否禁用loading ui的显示逻辑，
     * true为使用默认的加载ui（默认的加载ui也需要重写isEnableLoadingHelper() = true），
     * false则什么都不会发生
     */
    open val mIsEnableLoading = true

    /**
     * 是否使用自己的加载ui，需要mIsEnableLoading 设置为true，并重写customLoading()
     */
    open val mIsEnableUseCustomLoading = false

    /**
     * 同上
     */
    open val mIsEnableError = true

    open val mIsEnableUseCustomError = false

    /**
     * 同上
     */
    open val mIsEnableEmpty = true

    open val mIsEnableUseCustomEmpty = false

    /**
     * 同上
     */
    open val mIsEnableContent = true

    open val mIsEnableUseCustomContent = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        addLoadingDialogUIObserve()
        addLoadingHelperObserve()
        lifecycle.addObserver(viewModel)
    }

    /**
     * 状态页面占位
     */
    private fun addLoadingHelperObserve() {
        viewModel.loadingUiHelper.observe(this@BaseLoadingActivity) { loadingHelperUiState ->
            loadingHelperUiState?.run {
                Logger.i("loadingHelpType = ${loadingHelpType.name}")
                when (loadingHelpType) {
                    LoadingHelperType.LOADING -> {
                        loadingLogic(loadingHelperUiState)
                    }
                    LoadingHelperType.ERROR -> {
                        errorLogic(loadingHelperUiState)
                    }
                    LoadingHelperType.EMPTY -> {
                        emptyLogic(loadingHelperUiState)
                    }
                    LoadingHelperType.CONTENT -> {
                        contentLogic(loadingHelperUiState)
                    }
                }
            }
        }
    }

    private fun loadingLogic(loadingHelperUiState: LoadingHelperUiState) {
        if (!mIsEnableLoading) return

        if (mIsEnableUseCustomLoading) {
            customLoading()
        } else {
            if (isEnableLoadingHelper()) {
                mLoadingHelper!!.showLoadingView()
            }
        }
    }

    open fun customLoading() {}

    private fun errorLogic(loadingHelperUiState: LoadingHelperUiState) {
        if (!mIsEnableError) return

        if (mIsEnableUseCustomError) {
            customError(loadingHelperUiState)
        } else {
            if (isEnableLoadingHelper()) {
                val errorTip = loadingHelperUiState.stateData as String
                mLoadingHelper!!.getViewDelegate<ErrorAdapter>(ViewType.ERROR).run {
                    errorText = errorTip
                }
                mLoadingHelper!!.showErrorView()
            }
        }
    }

    open fun customError(loadingHelperUiState: LoadingHelperUiState) {
        if (isEnableLoadingHelper()) {
            mLoadingHelper!!.showContentView()
        }
    }

    private fun emptyLogic(loadingHelperUiState: LoadingHelperUiState) {
        if (!mIsEnableEmpty) return

        if (mIsEnableUseCustomEmpty) {
            customEmpty()
        } else {
            if (isEnableLoadingHelper()) {
                mLoadingHelper!!.showEmptyView()
            }
        }
    }

    open fun customEmpty() {
        if (isEnableLoadingHelper()) {
            mLoadingHelper!!.showContentView()
        }
    }

    private fun contentLogic(loadingHelperUiState: LoadingHelperUiState) {
        if (!mIsEnableContent) return

        if (mIsEnableUseCustomContent) {
            customContent()
        } else {
            if (isEnableLoadingHelper()) {
                mLoadingHelper!!.showContentView()
            }
        }
    }

    open fun customContent() {}

    open fun addLoadingDialogUIObserve() {
        viewModel.run {
            viewModel.loading.observe(this@BaseLoadingActivity, {
                if (it.stateType == StateType.LOADING_DIALOG) {
                    val data = it.stateData as LoadingDialog
                    when (data.loadingDialogStateType) {

                        LoadingDialogStateType.LOADING -> showLoadingView(data.tip)

                        LoadingDialogStateType.SUCCESS -> {
                            dismissLoadingView(data.showLoadingDelay, runnable = {
                                when{
                                    it.stateData.isShowDialogTip->{
                                        showResultPopupView(it.stateData, R.drawable.svg_success_remind)
                                    }
                                    it.stateData.isShowToastTip->{
                                        toast(data.tip)
                                        it.stateData.action?.invoke()
                                    }
                                }
                            })
                        }
                        LoadingDialogStateType.ERROR -> {
                            dismissLoadingView(data.showLoadingDelay, runnable = {
                                when{
                                    it.stateData.isShowDialogTip->{
                                        showResultPopupView(it.stateData, R.drawable.svg_fail_remind)
                                    }
                                    it.stateData.isShowToastTip->{
                                        toast(data.tip)
                                        it.stateData.action?.invoke()
                                    }
                                }
                            })
                        }
                        LoadingDialogStateType.DISMISS -> {
                            dismissLoadingView(data.showLoadingDelay) {
                                if(it.stateData.isShowToastTip){
                                    toast(data.tip)
                                    it.stateData.action?.invoke()
                                }
                            }
                        }
                    }
                }
            })
        }
    }

    /**
     * 如要自定义显示弹框则重新这个方法
     */
    open fun showResultPopupView(data: LoadingDialog, tipRes:Int){
        CreateXPopupHelper.createTipPopupView(PopupViewEntity().apply {
            context = this@BaseLoadingActivity
            isShow = true
            delay = data.showResultDelay
            tipResId = tipRes
            tipTitle = ""
            isDismissOnBackPressed = false
            isDismissOnTouchOutside = false
            tipMessage = data.tip
            tipDismissCallBack = {
                data.action?.invoke()
            }
        })
    }

    /**
     * 继承ILoading并在子类fragment重写showLoadingView可以随意替换加载弹窗，或者直接修改CustomLoadingPopupView布局
     */
    open fun showLoadingView(loadingText: String): ILoading? {
        if (mLoadingPopupView == null) {
            mLoadingPopupView = XPopup
                .Builder(this@BaseLoadingActivity)
                .dismissOnTouchOutside(false)
                .dismissOnBackPressed(false)
                .asCustom(CustomLoadingPopupView(this@BaseLoadingActivity))
                .show() as CustomLoadingPopupView
        }
        mLoadingPopupView?.setTitle(loadingText)
        mLoadingPopupView?.show()
        return mLoadingPopupView
    }

    /**
     * 关闭加载弹窗
     */
    open fun dismissLoadingView(delay: Long, runnable: Runnable = Runnable {}) {
        mLoadingPopupView?.run {
            delayDismissWith(delay, runnable)
        }
    }

    override fun onReload() {}

}

